<template>
  <div class="roles">
    <!-- 面包屑导航 -->
    <breadcrumb firstTitle="权限管理" secondTitle="角色列表"></breadcrumb>

    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="isShowRoleDialog=true">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['row_bb',index===0?'row_bt': '']" v-for="(items,index) in scope.row.children" :key="items.id" class="ac-row">
              <!--一级权限  -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,items.id)">{{ items.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 存放二级三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item,indey) in items.children" :key="item.id" :class="['ac-row',indey===0?'':'row_bt']">
                  <!--  二级权限  -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item.id)">{{ item.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item1, in item.children" :key="item1.id" closable @close="removeRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label='#'></el-table-column>
        <el-table-column prop="roleName" label='角色名称'></el-table-column>
        <el-table-column prop="roleDesc" label='角色描述'></el-table-column>
        <el-table-column label='操作'>
          <template slot-scope="scope">
            <el-tooltip content="编辑角色" placement="top" :enterable='false'>
              <el-button type="primary" icon="el-icon-edit" size='mini' @click="showEditorDialog(scope.row)">编辑</el-button>
            </el-tooltip>

            <el-tooltip content="删除角色" placement="top" :enterable='false'>
              <el-button type="danger" size='mini' icon="el-icon-delete" @click="removeRole(scope.row)">删除</el-button>
            </el-tooltip>

            <el-tooltip content="分配权限" placement="top" :enterable='false'>
              <el-button type="warning" size='mini' icon="el-icon-setting" @click="setShowRightDialog(scope.row)">分配权限</el-button>
            </el-tooltip>

          </template>

        </el-table-column>
      </el-table>

      <!-- 添加角色dialog -->
      <el-dialog :visible.sync="isShowRoleDialog" title="添加角色">
        <el-form :model="rolesForm" ref="ruleRolesRef" label-width="100px" :rules="addFormRules">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>

          <el-form-item label="角色描述:" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer">
          <el-button @click="isShowRoleDialog=false">取 消</el-button>
          <el-button type="primary" @click="addRule">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色dialog -->
      <el-dialog :visible.sync="isShowEditorDialog" title="编辑角色">
        <el-form label-width="100px" ref="editorRef" :model="editorForm" :rules="editFormRules">
          <el-form-item label="角色id:">
            <el-input v-model="editorForm.id" disabled></el-input>
          </el-form-item>

          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="editorForm.roleName"></el-input>
          </el-form-item>

          <el-form-item label="角色描述:" prop="roleDesc">
            <el-input v-model="editorForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowEditorDialog=false">取 消</el-button>
          <el-button type="primary" @click="updataRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限dialog -->
      <el-dialog title="分配权限" :visible.sync="isShowDistributionDialog" @close="setRightDialog">
        <el-tree :data="rightList" :props="rightProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="arr" ref="rightTree"></el-tree>
        <span slot="footer">
          <el-button @click="isShowDistributionDialog = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import request from '../../network/request'
import breadcrumb from '../breadcurmb/BreakCrumb.vue'
import { rolesFormRulesMixin } from '@/common/mixin'

export default {
  name: 'MyRoles',
  mixins: [rolesFormRulesMixin],
  created() {
    this.getRolesList()
  },
  data() {
    return {
      // 角色列表
      rolesList: [],
      isShowRoleDialog: false,
      rolesForm: {
        // 角色名称
        roleName: '',
        // 角色描述
        roleDesc: ''
      },
      // 控制显示与隐藏编辑对话框
      isShowEditorDialog: false,
      // 控制显示与隐藏分配对话框
      isShowDistributionDialog: false,
      // 编辑角色表单
      editorForm: {
        id: 0,
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色验证规则
      EditorFormRule: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述信息',
            trigger: 'blur'
          }
        ]
      },
      // 显示所有权限列表
      rightList: [],
      // 树形空间的循环规则
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 在分配角色dialog对话框中勾选的id值 包括半选中的节点和选中的节点
      arr: [],
      // 角色id
      roleId: 0
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await request('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 添加角色信息
    async addRule() {
      const { data: res } = await request.post('roles', this.rolesForm)
      if (res.meta.status !== 201) return this.$message.error('角色信息添加失败')

      // 重新获取角色列表
      this.getRolesList()
      this.isShowRoleDialog = false
    },
    // 点击编辑按钮
    showEditorDialog(val) {
      this.isShowEditorDialog = true
      this.editorForm.id = val.id
      this.editorForm.roleName = val.roleName
      this.editorForm.roleDesc = val.roleDesc
    },
    // 点击编辑dialog里面的确定按钮
    async updataRole() {
      const { data: res } = await request.put(`roles/${this.editorForm.id}`, this.editorForm)
      if (res.meta.status !== 200) return this.$message.error('角色信息编辑失败')
      this.isShowEditorDialog = false

      // 重新获取角色列表数据
      this.getRolesList()
    },
    // 展开展开列 删除权限
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除！')
      }

      const { data: res } = await request.delete(`roles/${role.id}/rights/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败')
      }
      this.$message.success('取消权限成功')
      role.children = res.data
    },
    // 点击分配权限按钮 弹出的对话框  并请求数据所有权限放到对话框中
    async setShowRightDialog(val) {
      this.roleId = val.id
      this.isShowDistributionDialog = true
      const { data: res } = await request('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('请求所有权限失败')
      this.rightList = res.data
      this.getArr(val, this.arr)
    },
    // 将所有权限的id放到数组中
    getArr(node, arr) {
      if (!node.children) return arr.push(node.id)

      node.children.forEach(item => {
        this.getArr(item, arr)
      })
    },
    // 每次关闭分配权限对话框都要清空一下arr数组 防止数组中id存放越来越多
    setRightDialog() {
      this.arr = []
    },
    // 点击分配角色权限按钮
    async allotRights() {
      const keys = [...this.$refs.rightTree.getCheckedKeys(), ...this.$refs.rightTree.getHalfCheckedKeys()]
      // 从数组变成了字符串
      const keysArr = keys.join(',')
      const { data: res } = await request.post(`roles/${this.roleId}/rights`, { rids: keysArr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')

      this.$message.success('分配权限成功')
      // 重新获取数据
      this.getRolesList()
      this.isShowDistributionDialog = false
    },
    // 删除角色
    async removeRole(val) {
      const resultRole = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resultRole !== 'confirm') {
        return this.$message.info('取消删除角色')
      }
      const { data: res } = await request.delete(`roles/${val.id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')

      // 重新渲染角色列表
      this.getRolesList()
    }
  },
  components: {
    breadcrumb
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding-bottom: 10px;
}
.el-dialog__footer span {
  display: flex;
  justify-content: center;
}
</style>